#!/usr/bin/env python
# coding=utf-8

from vavava.workqueue import Work
from . import track_db
import sys

class TaskWorkBase(Work):
    def __init__( self, track_type, period, group, begin_time=None,
                 end_time=None, log=None,**kvarg ):
        Work.__init__( self,period=period, group=group, begin_time=begin_time,
            end_time=end_time, log=log, name="" )
        self.track_type_      = track_type
        self._work_name       = "[%s]" % str(type(self))
        self.timeout_items_   = {}
        self.delivered_items_ = {}
        self.tracking_items_  = {}
        self.conn_            = None
        self.proxy_           = None
        if kvarg:
            proxy = kvarg.get("proxy")
            if proxy:
                self.proxy_ = kvarg["proxy"]
        self.redo_counter_ = sys.maxsize

    def _get_all_items(self):
        """ method to get all items """
        pass

    def _get_work_instance(self, itemID):
        """ method to get work instance """
        assert(False)

    def do(self,worker=None):
        if not worker:
            raise Exception("[%s] Unknown parent,cannot add work for main task. " % self._work_name )
        if self._work_param:
            self.conn_ = self._work_param
        elif self.conn_ is None and self._work_param is None:
            raise Exception("[%s] DBObj is Null." % self._work_name )
        self.log.info("[%s] AddTrackWork begin. [redo=%d,work_done=%s]"
                      % (self._work_name,self.redo_counter_, str(self._done)) )
        # get data from db
        db = track_db.TrackDB(db_conn=self.conn_,log=self.log)
        self.tracking_items_  = db.get_tracking_items(self.track_type_)
        self.delivered_items_ = db.get_delivered_items(self.track_type_)
        self.timeout_items_   = db.get_timeout_items(self.track_type_)
        self.log.info("[%s] Get db data:[tracking=%d,delivered=%d,timeout_items_=%d]"
                      % (self._work_name,len(self.tracking_items_),len(self.delivered_items_),len(self.timeout_items_)) )
        # get items from web
        all_items = self._get_all_items( )
        if all_items is None:
            all_items = self.tracking_items_
            self.log.warn("[%s]Failed to get item list from web." % self._work_name )
            # process data
        new_items_count = 0
        for item in all_items:
            tmp_dict=dict()
            if item in self.delivered_items_:
                continue
            if item in self.timeout_items_:
                continue
            if item not in self.tracking_items_:
                self.delivered_items_[item] = ""
                self.log.info( "[%s] New item:%s" % (self._work_name, item) )
                new_items_count += 1
            else:
                tmp_dict = db.item_get_top10(item,self.track_type_)
            # add to workshop
            work = self._get_work_instance( item_id=item )
            work.fetcher_.track_dict = tmp_dict
            worker._wq_parent.QueueWork(work=work)
            self.log.debug("[%s] Add db work to workshop. Item=%s"%(self._work_name,item))

        self.log.info("[%s] new_items_size=%d,tracking_items_=%d" %
                      (self._work_name,new_items_count,len(self.tracking_items_)) )

        self.redo_counter_ -= 1
        if self.redo_counter_ > 0:
            self._done = False # need start again
        else:
            self._done = True # do not need start again

        self.log.info("[%s] AddTrackWork ended. [redo=%d,work_done=%s]"
                      % (self._work_name,self.redo_counter_, str(self._done)) )
